package com.song.shop.dynamic;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Song Yinghui
 * @date 2018/9/29
 * @Version 1.0
 */

@Aspect
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(DS)")
    public void beforeSwitchDS(JoinPoint joinPoint){
        Class<?> className = joinPoint.getTarget().getClass();

        String name = joinPoint.getSignature().getName();

        Class[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
        String dataSource = DynamicDataSourceHolder.MASTER ;

        try{
            Method method = className.getMethod(name, parameterTypes);
            if (method.isAnnotationPresent(DS.class)){
                DS annotation = method.getAnnotation(DS.class);
                dataSource = annotation.value();
            }
        }catch(Exception e){
        }

        DynamicDataSourceHolder.setDataSource(dataSource);
    }

    @After("@annotation(DS)")
    public void afterSwitchDS(JoinPoint point){
        DynamicDataSourceHolder.clear();
    }

}
